function ShiftMat = getShiftedMat(Mat, dx, dy, Wrap)
%getShiftedMat Translates an nD array along its first two
%dimensions.
%
%   [ShiftMat,ROIStart_X,ROIStart_Y] =
%   getShiftedMat(Mat,dx,dy,Wrap) Given an initial matrix
%   Mat, returns a version shifted by dx along the x-direction
%   and dy along the y-direction. i.e ShiftMat(i,j,...) =
%   Mat(i-dy,j-dx,...). If Wrap = 0, coordinates beyond the
%   matrix are treated as zeros. If Wrap = 1, a circular shift
%   is performed.
%
%   TODO: allow to accept multiple Dxs and Dys (Dxs and Dys
%   matrices of the same shape). Return all requested shifts as
%   extra dimensions. So if Dx and Dy are KxL matrices and Mat is
%   NxM, would return a NxMxKxL matrix.
%
%see also circshift
if ~exist('Wrap','var')
    Wrap = 0;
end

if numel(dx)~=numel(dy)
    error('dx and dy must be same size');
end

if numel(dx) > 1
    %if dx is a matrix, call this function on each element of
    %dx.
    ShiftMat = zeros(size(Mat), size(dx));
    for ii = 1:numel(dx)
        ShiftMat(:, :, ii) = getShiftedMat(Mat, dx(ii), dy(ii), Wrap);
    end
else
    if Wrap
        ShiftMat = circshift(Mat, [dy, dx]);
    else
        ShiftMat = zeros(size(Mat));
        if ~isnumeric(Mat)
            disp('First argument not numeric')
        end
        if dx >= 0 && dy >= 0
            ShiftMat(dy+1:end, dx+1:end, :) = ...
                Mat(1:end-abs(dy),1:end-abs(dx),:);
        elseif dx >= 0 && dy < 0
            ShiftMat(1:end - abs(dy), dx+1:end, :) = ...
                Mat(abs(dy) + 1:end, 1:end-abs(dx) ,:);
        elseif dx < 0 && dy >= 0
            ShiftMat(dy + 1:end, 1:end - abs(dx), :) = ...
                Mat(1:end - abs(dy), abs(dx) + 1:end, :);
        elseif dx < 0 && dy < 0
            ShiftMat(1:end - abs(dy), 1:end - abs(dx), :) = ...
                Mat(abs(dy) + 1:end, abs(dx) + 1:end, :);
        end
        ROIStart_X = 1 - dx;
        ROIStart_Y = 1 - dy;
    end
end
end